package com.getpebble.android.main.sections.support.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.Analytics.Support;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.framework.fragment.PblBaseFragment;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.main.activity.MainActivity;
import com.getpebble.android.main.sections.appstore.fragment.NoConnectivityFragment;
import com.getpebble.android.main.sections.support.SupportEmail;
import com.getpebble.android.main.sections.support.SupportEmail.Callback;
import com.getpebble.android.main.sections.support.activity.FirmwareUpdateActivity;
import com.getpebble.android.main.sections.support.activity.NotificationDemoActivity;
import com.getpebble.android.util.HttpUtils;
import com.getpebble.android.widget.CustomToast;
import java.util.ArrayList;
import java.util.List;

public class SupportFragment extends PblBaseFragment implements OnItemClickListener {
    public static final String TAG = SupportFragment.class.getSimpleName();
    private SupportItemsAdapter mAdapter;
    private EmailTimeoutRunnable mEmailTimeoutRunnable;
    private final Handler mHandler = new Handler(Looper.getMainLooper());
    private ListView mListView;
    private ProgressDialog mProgressDialog;
    private TextView mVersionText;

    private class EmailTimeoutRunnable implements Runnable {
        private final SupportEmail email;

        public EmailTimeoutRunnable(SupportEmail email) {
            this.email = email;
        }

        public void run() {
            if (SupportFragment.this.isAdded()) {
                Trace.verbose(SupportFragment.TAG, "EmailTimeoutRunnable firing: isAdded; calling onEmailReady");
                SupportFragment.this.onEmailReady(this.email);
                return;
            }
            synchronized (SupportFragment.this) {
                Trace.verbose(SupportFragment.TAG, "EmailTimeoutRunnable firing: !isAdded; removing callbacks but not creating email");
                SupportFragment.this.mHandler.removeCallbacks(SupportFragment.this.mEmailTimeoutRunnable);
                SupportFragment.this.mEmailTimeoutRunnable = null;
            }
        }
    }

    private static class SupportItemsAdapter extends ArrayAdapter<SupportListItem> {
        private Context mContext;

        public SupportItemsAdapter(Context context, List<SupportListItem> items) {
            super(context, R.layout.support_list_item, items);
            this.mContext = context;
        }

        public int getTitleIdAtPosition(int position) {
            return ((SupportListItem) getItem(position)).titleResId;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(this.mContext).inflate(R.layout.support_list_item, null);
            }
            TextView summary = (TextView) convertView.findViewById(R.id.item_summary);
            ImageView icon = (ImageView) convertView.findViewById(R.id.item_icon);
            SupportListItem item = (SupportListItem) getItem(position);
            ((TextView) convertView.findViewById(R.id.item_title)).setText(item.titleResId);
            summary.setText(item.summaryResId);
            icon.setImageResource(item.iconResId);
            return convertView;
        }
    }

    private static class SupportListItem {
        public int iconResId;
        public int summaryResId;
        public int titleResId;

        public SupportListItem(int titleResId, int summaryResId, int iconResId) {
            this.titleResId = titleResId;
            this.summaryResId = summaryResId;
            this.iconResId = iconResId;
        }
    }

    public int getLayoutId() {
        return R.layout.fragment_support;
    }

    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        MobileAppBehavior.logScreenOpened("Support");
        this.mListView = (ListView) container.findViewById(16908298);
        this.mAdapter = new SupportItemsAdapter(getActivity(), getSupportListItems());
        this.mListView.setAdapter(this.mAdapter);
        this.mListView.setOnItemClickListener(this);
        this.mVersionText = (TextView) container.findViewById(R.id.version_text);
        ((Button) container.findViewById(R.id.btn_check_updates)).setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                MobileAppBehavior.logButtonTapped("startUpdate", "Support");
                Activity activity = SupportFragment.this.getActivity();
                if (activity == null) {
                    Trace.error(SupportFragment.TAG, "OnClick CheckUpdateButton: activity was null");
                } else if (HttpUtils.hasInternetConnection(activity.getApplicationContext())) {
                    SupportFragment.this.startActivity(new Intent(activity, FirmwareUpdateActivity.class));
                } else if (activity instanceof MainActivity) {
                    ((MainActivity) activity).switchFragment(new NoConnectivityFragment(), false, false, true);
                }
            }
        });
    }

    public void onResume() {
        super.onResume();
        updateVersionText();
        handleArguments();
    }

    private void updateVersionText() {
        this.mVersionText.setText(String.format(getString(R.string.support_version_format), new Object[]{getAppVersionName(), getWatchVersionName()}));
    }

    private void handleArguments() {
        Bundle args = getArguments();
        if (args != null && args.containsKey("support_email_request") && args.getBoolean("support_email_request")) {
            boolean includeLogs = args.getBoolean("include_logs");
            Trace.verbose(TAG, "Starting support email from arguments");
            startSupportEmailTasks(includeLogs);
            getArguments().remove("support_email_request");
            getArguments().remove("include_logs");
        }
    }

    private String getAppVersionName() {
        Context context = getActivity();
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            Trace.error(TAG, "Unable to determine version name:", e);
            return "";
        }
    }

    private String getWatchVersionName() {
        PblDeviceRecord connectedDevice = PebbleApplication.getConnectedDeviceRecord();
        if (connectedDevice == null) {
            return getString(R.string.support_version_not_connected);
        }
        if (connectedDevice.fwVersion == null) {
            return getString(R.string.support_version_unknown);
        }
        return connectedDevice.fwVersion.getVersionTag();
    }

    private List<SupportListItem> getSupportListItems() {
        List<SupportListItem> items = new ArrayList();
        items.add(new SupportListItem(R.string.support_getting_started_label, R.string.support_getting_started_summary, R.drawable.support_icon_getting_started));
        items.add(new SupportListItem(R.string.support_faq_label, R.string.support_faq_summary, R.drawable.support_icon_faq));
        items.add(new SupportListItem(R.string.support_community_label, R.string.support_community_summary, R.drawable.support_icon_community));
        items.add(new SupportListItem(R.string.support_helpdesk_label, R.string.support_helpdesk_summary, R.drawable.support_icon_helpdesk));
        items.add(new SupportListItem(R.string.support_suggest_label, R.string.support_suggest_summary, R.drawable.support_icon_suggest));
        items.add(new SupportListItem(R.string.support_test_notifications_label, R.string.support_test_notifications_summary, R.drawable.support_icon_test_notifications));
        return items;
    }

    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        switch (this.mAdapter.getTitleIdAtPosition(position)) {
            case R.string.support_community_label:
                launchUrl(PebbleApplication.getBootConfig().getSupportCommunityUrl());
                Support.logSupportCommunityTapped();
                return;
            case R.string.support_faq_label:
                launchUrl(PebbleApplication.getBootConfig().getSupportFAQUrl());
                Support.logSupportFaqTapped();
                return;
            case R.string.support_getting_started_label:
                launchUrl(PebbleApplication.getBootConfig().getSupportGettingStartedUrl());
                Support.logSupportGettingStartedTapped();
                return;
            case R.string.support_helpdesk_label:
                Trace.verbose(TAG, "Starting support email from menu item click");
                startSupportEmailTasks(true);
                Support.logSupportContactSupportTapped();
                return;
            case R.string.support_suggest_label:
                launchUrl(PebbleApplication.getBootConfig().getSupportSuggestSomethingUrl());
                Support.logSupportSuggestSomethingTapped();
                return;
            case R.string.support_test_notifications_label:
                startActivity(new Intent(getActivity(), NotificationDemoActivity.class));
                Support.logSupportTestNotificationsTapped();
                return;
            default:
                return;
        }
    }

    private void launchUrl(String url) {
        getActivity().startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
    }

    private synchronized void startSupportEmailTasks(boolean includeLogs) {
        Trace.debug(TAG, "Starting support email tasks");
        if (this.mEmailTimeoutRunnable != null) {
            Trace.info(TAG, "Skipping support email request (operations pending)");
        } else {
            showProgressDialog(getResources().getString(R.string.support_preparing_email));
            this.mEmailTimeoutRunnable = new EmailTimeoutRunnable(new SupportEmail(getActivity(), includeLogs, new Callback() {
                public void onComplete(SupportEmail completeEmail) {
                    if (SupportFragment.this.isAdded()) {
                        SupportFragment.this.onEmailReady(completeEmail);
                    } else {
                        Trace.info(SupportFragment.TAG, "E-mail ready, but fragment not added");
                    }
                }

                public void onPing() {
                    synchronized (SupportFragment.this) {
                        if (SupportFragment.this.mEmailTimeoutRunnable == null) {
                            Trace.warning(SupportFragment.TAG, "onPing; mEmailTimeoutRunnable is null, not resetting timeout");
                            return;
                        }
                        Trace.verbose(SupportFragment.TAG, "onPing; resetting timeout");
                        SupportFragment.this.mHandler.removeCallbacks(SupportFragment.this.mEmailTimeoutRunnable);
                        SupportFragment.this.mHandler.postDelayed(SupportFragment.this.mEmailTimeoutRunnable, 25000);
                    }
                }
            }));
            this.mHandler.postDelayed(this.mEmailTimeoutRunnable, 25000);
        }
    }

    private synchronized void onEmailReady(SupportEmail email) {
        if (this.mEmailTimeoutRunnable == null) {
            Trace.debug(TAG, "onEmailReady; already sent email for this task");
        } else {
            this.mHandler.removeCallbacks(this.mEmailTimeoutRunnable);
            this.mEmailTimeoutRunnable = null;
            final Activity activity = getActivity();
            if (activity == null) {
                Trace.info(TAG, "Fragment not added, aborting");
            } else {
                try {
                    startActivity(Intent.createChooser(email.generateIntent(), getResources().getString(R.string.support_select_an_email_client)));
                } catch (Exception e) {
                    Trace.error(TAG, "Unable to launch e-mail for the user", e);
                    activity.runOnUiThread(new Runnable() {
                        public void run() {
                            CustomToast.show(activity, SupportFragment.this.getResources().getString(R.string.support_preparing_email_failed), 1);
                        }
                    });
                }
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        SupportFragment.this.hideProgressDialog();
                    }
                });
            }
        }
    }

    private void showProgressDialog(String message) {
        if (isAdded()) {
            if (this.mProgressDialog == null) {
                this.mProgressDialog = new ProgressDialog(getActivity(), 0);
                this.mProgressDialog.setCancelable(false);
            }
            if (!TextUtils.isEmpty(message)) {
                this.mProgressDialog.setMessage(message);
                this.mProgressDialog.show();
            }
        }
    }

    private void hideProgressDialog() {
        if (isAdded() && this.mProgressDialog != null) {
            this.mProgressDialog.dismiss();
        }
    }
}
